var processUrl = 'saveFile.php';
var dirUrl = 'dir.php';
var icelTemplate = {'dbId': 'Database ID'};
var readingTemplate = {'synopsis': 'Synopsis', 'reference': 'Reference', 'introduction': 'Introduction'}
var templates = {
'hymn-texts/': {'name':'Name','source':'Source','meter':'Meter','author':'Author','translator':'Translator','theme':'Theme','copyright':'Copyright','ignoreMelismata':'<label>Ignore Melismata</label><input type="checkbox"/><br/>','refrain':'<label>Refrain</label><br/><div class="tap" style="padding-bottom:4px"><textarea style="width:100%;font-size:11pt;height:10px"/></div>'},
'verses/~/': {'title':'Title'},
'texts/antiphons/': {'text-left':'Left', 'text-right':'Right'},
'score-templates/': {
    'size6': 'Size 6',
    'size7': 'Size 7',
    'size8': 'Size 8',
    'size10': 'Size 10',
    'size12': 'Size 12',
    'size13.5': 'Size 13.5 (genre only)',
    'size14': 'Size 14',
    'size15': 'Size 15 (rubric title only)',
    'size16': 'Size 16',
    'size17': 'Gregorio Staff Size (17)',
    'size18': 'Size 18',
    'size38': 'Size 38',
    'marginNumSize': 'Margin Number Size',
    'marginNumBold': '<label>Bold Margin Numbers</label><input type="checkbox"/><br/>',
    'staffsize': 'Staff Size (16)',
    'lyricsize': 'Relative Lyric Size (1.5)',
    'width': 'Content Width (4.5)',
    'vwidth': 'Verse Width (4.5)',
    'pwidth': 'Page Width (6)',
    'height': 'Height (9)',
    'topmargin': 'Top Margin (0.6)',
    'bottommargin': 'Bottom Margin (0.6917)'
  },
'texts/psalm-responses_ICEL-1997/': icelTemplate,
'texts/gospel-verses_ICEL-1997/': icelTemplate,
'texts/lenten-gospel-acclamations_ICEL-1997/': icelTemplate,
'texts/readings/': readingTemplate
};
var selTemplate = '';

function saveFile(e) {
  var text = $("#editor").val();
  var fileName = $("#lnkSave").data('name');
  if(selTemplate){
    var data = {text:text};
    for(var v in templates[selTemplate]){
      var $input = $('#var-' + v);
      data[v] = $input.is(':checkbox')?
        $input.prop('checked') : $input.val();
    }
    text = JSON.stringify(data);
  }
  var data = {name:fileName,text:text};
  $.post(processUrl,data,function(data){
    if(data==''){
      console.info("Successfully saved " + fileName);
      var $span = $("<span>Success</span>");
      $("#notification").append($span);
      setTimeout(function(){
        $span.fadeOut();
      },1000);
    } else {
      console.warn("Failed to save " + fileName);
      console.warn(data);
      var $span = $("<span>FAILED</span>");
      $("#notification").append($span);
      setTimeout(function(){
        $span.fadeOut();
      },1000);
    }
  });
  if(e && typeof(e.preventDefault)=='function') e.preventDefault();
}

function docKeyDown(e){
  if(e.ctrlKey) {
    if(e.which==83) {//S
      //save
      e.preventDefault();
      saveFile();
    }
  }
}

function keyUpBoldItalic(e) {
  if(!e.altKey) return;
  var mark = '';
  switch(e.which) {
    case 66://B
      mark = '|';
      break;
    case 73://I
      mark = '_';
      break
    default:
      return;
  }
  var selStart = this.selectionStart,
      selEnd = this.selectionEnd,
      selLen = this.selectionEnd - this.selectionStart;
  var $this = $(this), txt = $this.val();
  e.preventDefault();
  if(selLen == 0) this.selectionEnd += 1;
  if(selLen > 1) isLetter = true;
  $this.val(txt.slice(0,this.selectionStart) + mark + txt.slice(this.selectionStart,this.selectionEnd) + mark + txt.slice(this.selectionEnd));
  this.selectionStart = selStart + 1;
  this.selectionEnd = selEnd + 1;
}

var dirs = {};
var activeDir;
var activeFile = '';
function folderContents(folder,contents){
  dirs[folder] = contents;
  if(activeDir == folder){
    setActiveContents(contents);
  }
}
function setActiveDir(dir){
  activeDir = dir;
  if(dir in dirs){
    setActiveContents(dirs[activeDir]);
  }
  $.getScript(dirUrl + '?dir=' + encodeURI(activeDir));
}
function setActiveContents(contents){
  contents.sort(function(a,b){
    var aa = parseInt(a);
    var ab = parseInt(b);
    if(isNaN(aa) || isNaN(ab)) {
      if(isNaN(aa) && isNaN(ab)) {
        return a > b?1 : -1;
      }
      return isNaN(aa);
    }
    return aa - ab;
  });
  var files='';
  var directories='';
  if(activeDir.length){
    var match = activeDir.match(/.*\/(?=.)/);
    directories += '<a class="link uplevel" href="#' + encodeURI((match&&match[0])||'') + '">[Up one level]</a><br/>';
  }
  for(var i=0; i<contents.length; ++i) {
    var item = contents[i];
    if(item.match(/\.(?:txt)$/i)){
      files += '<a class="link file" href="#' + encodeURI(activeDir + item) + '" path="' + activeDir + item + '">' + item + '</a><br/>';
    } else if(item.match(/\/$/)){
      directories += '<a class="link dir" href="#' + encodeURI(activeDir + item) + '" path="' + activeDir + item + '">' + item + '</a><br/>';
    }
  }
  $("#activeDir").text(activeDir);
  $("#fileList").empty().append(directories + files);
}
function hashChanged(e){
  var hash = window.location.hash.slice(1);
  if(hash.length == 0 || hash.slice(-1) == '/') {
    setActiveDir(hash);
  } else {
    var fileName = hash;
    setTemplateForFile(fileName);
    var match = hash.match(/.*\/(?=.)/);
    var dir = (match&&match[0]) || '';
    if(dir!=activeDir) setActiveDir(dir);
    $("sFileName").text("");
    activeFile = fileName;
    $("#lnkSave").data("name",fileName);
    $("#sFileName").text(' ' + fileName);
    $.get('get.php?file='+fileName,function(data,textStatus,jqXHR){
      if(selTemplate) {
        var data;
        try {
          data = JSON.parse(data);
        } catch(ex) {
          data = {'text':data};
        }
        for(var v in templates[selTemplate]) {
          var $input = $('#var-' + v);
          if($input.is(':checkbox')) {
            $input.prop('checked',data[v]);
          } else {
            $input.val(data[v]).trigger('autosize.resize');
          }
        }
        $("#editor").val(data.text || '').focus();
      } else {
        $("#editor").val(data).focus();
      }
    },'text')
  }
};

function clearEditor(e){
  e.preventDefault();
  $("#editor").val("").focus();
}

function syllabifyText(e){
  e.preventDefault();
  if(Dic && typeof(Dic.syllabify=='function')) {
    var fmt = activeDir.match('^(verses/|texts/antiphons/)')? null : Dic.lilypond;
    var $editor = $("#editor");
    $editor.val(Dic.syllabify($editor.val(),fmt,function(){
      $editor.val(Dic.syllabify($editor.val(),fmt));
    }));
  }
}

function clickedFileLink(e) {
  var path = $(this).attr('path');
  
}
function loadSelect(e,ui){
  if(ui.item.value.slice(-1)=='/') {
    $(this).autocomplete('search', ui.item.value);
  } else {
    location.hash = '#' + ui.item.value;
  }
}
function windowResized(){
  var $ed = $("#editor");
  var $txtLoad = $('#txtLoad');
  var discrepancy = $txtLoad.outerWidth(true) - $txtLoad.width() + 1;
  $txtLoad.width($txtLoad.parent().width() - $($txtLoad.prop('labels')).width() - discrepancy);
  $('input.resize').width(function(){
    var $this=$(this);
    return $this.parent().width() - $($this.prop('labels')).width() - discrepancy;
  });
  
  var totalHeight = $(window).height() - $ed.position().top;
  discrepancy = $ed.outerHeight(true) - $ed.height();
  $ed.height(totalHeight - discrepancy - 8);
  
}

function setTemplateForFile(fileName) {
  if(fileName.slice(-4) != '.txt') {
    for(t in templates) {
      var s = fileName[0]=='~'?1:0;
      if(fileName.slice(s,s+t.length)==t){
        loadTemplate(t);
        return;
      }
    }
  }
  loadTemplate('');
}

function txtLoadKeyup(e) {
  var fileName = $(this).val();
  setTemplateForFile(fileName);
  if(fileName.match(/^~?(?:texts|verses|hymn-texts|footers|score-templates)\/./)) {
    if(selTemplate) {
      if(!fileName.match(/\.json$/)) {
        fileName = fileName.replace(/\..{0,4}$|$/,'.json');
      }
    }
    $("#lnkSave").data("name",fileName);
    $("#sFileName").text(' ' + fileName);
  } else {
    $("#lnkSave").data("name",'');
    $("#sFileName").text('');
  }
}

function loadTemplate(template) {
  if(template != selTemplate) {
    selTemplate = template;
    var t = templates[selTemplate],
        $templateFields = $('#templateFields').empty();
    for(var v in t) {
      var lbl = t[v],
          $html = lbl[0]=='<'? $(lbl) : $('<label/><input type="text" spellcheck="false" class="resize"/>'),
          $lbl = $html.filter('label').add($html.find('label')).text(function(i,v){return v || (lbl+' ');}).attr('for','var-'+v);
          $input = $html.filter('input,textarea').add($html.find('input,textarea')).attr('id','var-'+v).attr('name',v);
      $templateFields.append($html);
      $html.filter('textarea').add($html.find('textarea')).autosize({callback:windowResized})
    }
    windowResized();
  }
}

function editorKeyDown(e){
  if(e.ctrlKey) {
    var code = '';
    switch(e.which) {
      case 192:
        code = e.shiftKey? '~' : '`';
        break;
      case 222:
        code = e.shiftKey? '"' : "'";
        break;
      case 54:
        if(e.shiftKey) code = '^';
        break;        
      case 72:
        if(e.shiftKey) code = 'H';
        break;
      case 67:
        code = 'c';
        break;
      case 75:
        code = 'k';
        break;
      case 76:
        code = 'l';
        break;
      case 187:
        code = '=';
        break;
      case 66:
        code = 'b';
        break;
      case 190:
      case 110:
        code = '.';
        break;
      case 68:
        code = 'd';
        break;
      case 82:
        code = 'r';
        break;
      case 85:
        code = 'u';
        break;
      case 86:
        code = 'v';
        break;
      case 84:
        code = 't';
        break;
    }
    var selStart = this.selectionStart,
        selEnd = this.selectionEnd,
        selLen = this.selectionEnd - this.selectionStart;
    if(code.length==1 && selLen <=2) {
      var $this = $(this), txt = $this.val(), isLetter = code.match(/[a-z]/i);
      e.preventDefault();
      if(selLen == 0) this.selectionEnd += 1;
      if(selLen > 1) isLetter = true;
      $this.val(txt.slice(0,this.selectionStart) + '\\' + code + (isLetter?'{':'') + txt.slice(this.selectionStart,this.selectionEnd) + (isLetter?'}':'') + txt.slice(this.selectionEnd));
      this.selectionStart = selStart + 2 + (isLetter? 1 : 0);
      this.selectionEnd = selEnd + 2 + (isLetter? 1 : 0);
    }
  }
}

$(function() {
  $(window).resize(windowResized);
  $("#lnkSave").click(saveFile);
  $("#lnkClearEditor").click(clearEditor);
  $("#lnkSyllabify").click(syllabifyText);
  $('#txtLoad').click(function(){$(this).autocomplete('search');}).autocomplete({
    source: 'ac.php?root=["texts/","verses/","hymn-texts/","autocompletes/","footers/","score-templates/"]&extension=txt|json',
    select: loadSelect,
    minLength: 0
  }).keyup(txtLoadKeyup);
  $('#editor').keydown(editorKeyDown).keyup(keyUpBoldItalic);
  
  $(document.body)
    .on("click","a.file",clickedFileLink);
  $.ajaxSetup({cache: false});
  if(location.protocol.slice(0,4) != "http" ||
     !location.hostname.match(/(?:apps\.)?(?:illuminarepublications|sacredmusicproject)\.com/i)
    ) {
    processUrl = "http://apps.illuminarepublications.com/editor/saveFile.php";
    dirUrl = "http://apps.illuminarepublications.com/dev-beta/dir.php";
    $("#imageForm,#pdfForm").attr("action",processUrl);
  }
  folderContents('',['verses/','texts/']);
  setActiveDir('');
  $(window).on("hashchange",hashChanged)
  $(document).keydown(docKeyDown);
  if(window.location.hash.slice(1).indexOf('/')>0) {
    hashChanged();
  } else {
    window.location.hash = "#";
  }
  setTimeout(windowResized,50);
});